스크롤 계산, scrollTo

마지막 수정일: 2025. 09. 17.

스크롤 애니메이션 계산하는 거 매번 헷갈려서 정리
사진은 중앙 정렬 예시

예시 코드

TYPESCRIPT
const container = asideElement as HTMLElement
const target = targetElement as HTMLElement

const crect = container.getBoundingClientRect()
const trect = target.getBoundingClientRect()

const Hc = container.clientHeight
const Ht = trect.height

// 타겟 상단의 콘텐츠 좌표 = container.scrollTop + (trect.top - crect.top)
const T = container.scrollTop + (trect.top - crect.top)
const nextScrollTop = T + Ht / 2 - Hc / 2

const minTop = 0
const maxTop = container.scrollHeight - container.clientHeight

container.scrollTo({
  top: Math.min(maxTop, Math.max(minTop, nextScrollTop)),
  behavior: "smooth",
})
TYPESCRIPT
const scrollSelectedIntoView = (index: number) => {
	if (index < 0) return
		const asideElement = document.querySelector(".records-aside")
		const targetElement = document.querySelector(
		`[data-record-index="${index}"]`,
	)
	if (asideElement && targetElement) {
		const asideHeight = (asideElement as HTMLElement).clientHeight
		const targetHeight = (targetElement as HTMLElement).clientHeight
		const scrollTo =
			(targetElement as HTMLElement).offsetTop -
			asideHeight / 2 +
			targetHeight / 2
			;(asideElement as HTMLElement).scrollTo({
			top: Math.max(0, scrollTo),
			behavior: "smooth",
		})
	}
}